<template>
  <div>
    <div class="flex">
      <div
        class="name text-right"
        style="padding-right: 6px;min-width: 86px;width: auto"
      >{{title}}:</div>
      <ul class="file-list flex-1">
        <li
          v-for="(file, fileIndex) in imgList"
          :key="fileIndex"
          class="file-item"
          v-show="!file.isDelete"
        >
          <span
            @click="lookDetail(file, fileIndex)"
            class="ellipsis cursor-pointer"
            style="display: inline-block;width: 114px"
          >{{file.name}}</span>
          <q-icon
            @click="delImg(fileIndex)"
            class="close fr"
            name="iconfont icontubiao-89"
          />
          <q-tooltip>{{file.name}}</q-tooltip>
        </li>
        <li
          class="add-item relative-position"
          v-if="imgList.length < max"
        >
          <form id="selImg">
            <q-icon
              name="iconfont icontubiao-39"
              class="add-icon"
            />添加新文件
            <input
              type="file"
              @input="addImg($event)"
              :multiple ="this.max > 1"
              class="q-uploader__input overflow-hidden absolute-full"
              :accept="accept"
            >
          </form>
        </li>
      </ul>
    </div>
    <look-img ref="lookImg"/>
    <!--查看pdf-->
    <look-pdf ref="LookPdf" />
  </div>
</template>

<script>
import LookImg from 'src/components/look-img'
import lookPdf from 'src/components/look-pdf'
import { uploadFlie } from 'src/boot/template/template-upload'
import _ from 'lodash'
import { mapGetters } from 'vuex'
export default {
  name: 'upload-picture',
  components: { LookImg, lookPdf },
  props: {
    value: [Array],
    title: {
      type: String,
      default: '上传图片'
    },
    max: {
      type: Number,
      default: 9
    },
    // 是否支持pfg格式
    imgPdf: {
      type: Boolean,
      default: false
    },
    size: {
      type: Number,
      default: 0
    },
    // 是否全量上传
    isUploadAll: {
      type: Boolean,
      default: false
    },
    // 编辑时 可以产看pdf 格式图片
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      imgList: [],
      errList: [],
      photoArray: []
    }
  },
  watch: {
    value: {
      handler (val) {
        this.imgList = val
      },
      deep: true,
      immediate: true
    },
    imgList: {
      deep: true,
      handler () {
        this.$emit('input', this.imgList)
      }
    },
    options (newPro) {
      this.fuzzyOptions = newPro || []
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ]),
    accept () {
      return this.imgPdf ? 'image/*, application/pdf' : 'image/*'
    }
  },
  methods: {
    addImg (event) {
      console.log(event)
      if (event.target.files.length === 0) {
        return
      }

      if (
        event.target.files.length > this.max ||
        event.target.files.length + (this.imgList.length || 0) > this.max
      ) {
        this.$showErrTips(`最多只能上传${this.max}张`)
        return
      }
      let hasFile = false
      let isLong = false
      for (let i = 0; i < event.target.files.length; i++) {
        const item = event.target.files[i]
        const type = _.split(item.type, '/')
        if (item.name.length > 80) {
          isLong = true
        } else {
          if (type[0] === 'image' || (this.imgPdf && type[1] === 'pdf')) {
            const files = [
              {
                name: item.name
              }
            ]
            let res = this.$getUploadPath(
              files,
              this.CommonConfig.ossFilePath.repairDir
            )
            let params = {
              id: res.fileNameNew,
              name: item.name,
              uploadPath: res.uploadPath,
              file: item,
              url: window.URL.createObjectURL(item)
            }
            this.imgList.push(params)
          } else {
            hasFile = true
          }
        }
      }
      document.getElementById('selImg').reset()
      isLong && this.$showErrTips('文件名过长，操作失败')
      hasFile && !this.imgPdf && this.$showErrTips('只可上传图片')
      hasFile && this.imgPdf && this.$showErrTips('只可上传图片或pdf文件')
    },
    delImg (index) {
      const imgList = _.cloneDeep(this.imgList)
      _.remove(imgList, function (n, i) {
        return i === index
      })
      this.imgList = imgList
    },
    // 查看文件详情
    lookDetail (item, index) {
      const imgList = _.map(this.imgList, 'url')
      if (this.imgPdf && !this.isImg(item.name)) {
        this.isEdit && _.isNil(item.file) ? this.$refs.LookPdf.showDialog(imgList[index]) : this.$message.warning('未上传pdf格式文件不支持预览')
        return
      }
      this.imgPdf ? this.$refs.lookImg.showDialog(imgList[index]) : this.$refs.lookImg.showDialog(imgList, index)
    },
    isImg (name) {
      let index = name.lastIndexOf('.')
      let ext = name.substr(index + 1)
      return ['png', 'jpg', 'jpeg'].indexOf(ext.toLowerCase()) !== -1
    },
    // 订阅上传
    uploadFlie (item) {
      if (_.isNil(item.file)) {
        this.photoArray.push(item)
        return
      }
      this.onSubscribe(item.id)
      uploadFlie(item.uploadPath, item.file, item.id).then(res => {
        if (res.code !== '1200') {
          this.closeUbscribeTopic(item.id, 'errList')
        }
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic(item.id, 'errList')
      })
    },
    onSubscribe (id) {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${id}`, this.onMessageArrived, { id: `${id}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      const imgItem = this.imgList.filter(item => item.id === msg.requestId)
      if (!imgItem.length) {
        return
      }
      // 失败
      if (msg.code + '' !== '200') {
        this.closeUbscribeTopic(msg.requestId, 'errList')
        return
      }
      const params = {
        name: imgItem[0].name,
        url: msg.data
      }
      this.closeUbscribeTopic(msg.requestId, 'photoArray', params)
    },
    closeUbscribeTopic (id, type, params) {
      this.client.unsubscribe(`${id}`)
      // 向成功/失败list中放信息
      if (type === 'photoArray') {
        this[type].push(params)
      } else {
        this[type].push(id)
      }
      // 全部文件上传成功，调用保存
      if ((this.errList.length + this.photoArray.length) >= this.imgList.length) {
        this.submitData()
      }
    },
    submitData () {
      if (this.errList.length) {
        let errMsg = '以下图片上传失败，请确认后重试：'
        this.errList.forEach(item => {
          const imgItem = this.imgList
          if (imgItem.length) {
            errMsg += imgItem[0].name + '、'
          }
        })
        errMsg = _.trimEnd(errMsg, '、')
        this.$showErrTips(errMsg)
        this.$q.loading.hide()
        this.errList = []
      } else {
        this.$emit('uploadImg', this.photoArray)
        // 清空历史图片
        this.photoArray = []
      }
    }
  },
  mounted () {}
}
</script>
<style scoped lang="stylus">
.file-list {
  flex: 1;
  display: flex;
  flex-wrap: wrap;

  .file-item {
    margin-bottom: 10px;
    margin-right: 16px;
    display: inline-block;
    padding: 0 10px;
    width: 150px;
    height: 32px;
    line-height: 32px;
    color: #fff;
    background: #F7B82D;
    box-shadow: 0px 1px 5px 0px rgba(0, 0, 0, 0.15);
    border-radius: 6px;

    .close {
      margin-top: 8px;
      opacity: 0.6;
    }
  }

  .add-item {
    margin-bottom: 10px;
    margin-right: 16px;
    display: inline-block;
    padding: 0 10px;
    width: 150px;
    height: 32px;
    line-height: 32px;
    color: #999;
    background: #fff;
    border-radius: 6px;
    border: 1px dashed #999;
    text-align: center;

    .add-icon {
      margin-right: 9px;
      font-size: 18px;
      position: relative;
      top: -1px;
    }
  }
}
</style>
